package ch.drshit.controller.listener;

import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JScrollBar;

import ch.drshit.controller.Controller;
import ch.drshit.view.swing.MyJComponent;

public class ImageMoveResizeController implements MouseWheelListener,
		KeyListener, AdjustmentListener  {
	private Controller controller;

	private boolean isCtrlPressed = false;

	public ImageMoveResizeController(Controller controller) {
		this.controller = controller;
	}

	@Override
	public void mouseWheelMoved(MouseWheelEvent e) {
		if (isCtrlPressed) {
			MyJComponent jcomp = this.getController().getView().getFrame()
					.getJcomponent();
			jcomp.setXadjust(0);
			jcomp.setYadjust(0);
			
			if (e.getWheelRotation() < 0) {
				jcomp.upZoomlevel();
			} else {
				jcomp.downZoomlevel();
			}
			this.getController().getView().getFrame().calcScrollbars();
		}else{
			JScrollBar bar = this.getController().getView().getFrame().getJscrollvertical();
			int val = bar.getValue();
			if(val + e.getScrollAmount() > 0){
				bar.setValue(val + e.getWheelRotation() * 10);
			}
		}
	}



	@Override
	public void keyPressed(KeyEvent arg0) {
		if (arg0.getKeyCode() == KeyEvent.VK_CONTROL) {
			isCtrlPressed = true;
		}
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		if (arg0.getKeyCode() == KeyEvent.VK_CONTROL) {
			isCtrlPressed = false;
		}
	}
	
	@Override
	public void adjustmentValueChanged(AdjustmentEvent arg0) {
		JScrollBar dragged = (JScrollBar) arg0.getSource();
		MyJComponent jcomp = this.getController().getView().getFrame().getJcomponent();
		if(dragged.getName().equals("h")){
			jcomp.setXadjust(-arg0.getValue());
		}else{
			jcomp.setYadjust(-arg0.getValue());
		}
		jcomp.repaint();
	}
	
	@Override
	public void keyTyped(KeyEvent arg0) {
		// nothing
	}

	public Controller getController() {
		return controller;
	}


}
